<template>
  <div class="home-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <div class="data-content">
            <div class="data-icon user-icon">
              <el-icon>
                <User />
              </el-icon>
            </div>
            <div class="data-info">
              <div class="data-title">用户总数</div>
              <div class="data-number">{{ stats.userCount.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <div class="data-content">
            <div class="data-icon shop-icon">
              <el-icon>
                <Shop />
              </el-icon>
            </div>
            <div class="data-info">
              <div class="data-title">商家数量</div>
              <div class="data-number">{{ stats.businessCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <div class="data-content">
            <div class="data-icon goods-icon">
              <el-icon>
                <Goods />
              </el-icon>
            </div>
            <div class="data-info">
              <div class="data-title">商品总数</div>
              <div class="data-number">{{ stats.goodsCount.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <div class="data-content">
            <div class="data-icon order-icon">
              <el-icon>
                <Document />
              </el-icon>
            </div>
            <div class="data-info">
              <div class="data-title">今日订单</div>
              <div class="data-number">{{ stats.todayOrderCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作区域 -->
    <el-card class="quick-actions" shadow="never">
      <template #header>
        <div class="clearfix">
          <span>快捷操作</span>
        </div>
      </template>
      <el-row :gutter="20" style="display: flex;justify-content: space-around;">
        <el-col v-for="(item, index) in quickActions" :key="index" :span="4" class="quick-item-col">
          <div class="quick-item" @click="handleQuickAction(item)" @keyup.enter="handleQuickAction(item)" tabindex="0"
            :aria-label="item.label" role="button">
            <el-icon>
              <component :is="item.icon" />
            </el-icon>
            <span>{{ item.label }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表展示区域 -->
    <el-row :gutter="20" class="chart-area">
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="clearfix">
              <span>近7日订单趋势</span>
            </div>
          </template>
          <div class="chart-container" ref="orderChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="clearfix">
              <span>用户增长统计</span>
            </div>
          </template>
          <div class="chart-container" ref="userChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  User,
  Shop,
  Goods,
  Document,
  Menu,
  Money
} from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()

// 快捷操作项
const quickActions = [
  { icon: 'User', label: '用户管理', path: '/user' },
  { icon: 'Shop', label: '商家管理', path: '/shop' },
  { icon: 'Goods', label: '商品管理', path: '/goods' },
  { icon: 'Document', label: '订单管理', path: '/order' },
  { icon: 'Menu', label: '分类管理', path: '/category' },
  // { icon: 'Money', label: '充值记录', path: '/recharge' }
]

// 统计数据
const stats = ref({
  userCount: 0,
  businessCount: 0,
  goodsCount: 0,
  todayOrderCount: 0
})

// 图表实例引用
const orderChartRef = ref(null)
const userChartRef = ref(null)
let orderChart = null
let userChart = null

// 处理快捷操作点击
const handleQuickAction = (item) => {
  router.push(item.path)
}

// 获取首页统计数据
const fetchDashboardStats = async () => {
  try {
    const response = await axios.get('http://localhost:8889/api/admin/dashboard/stats')
    if (response.data.code === 200) {
      stats.value = response.data.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取订单趋势数据并初始化图表
const initOrderChart = async () => {
  if (!orderChartRef.value) return

  try {
    const response = await axios.get('http://localhost:8889/api/admin/dashboard/order-trend')
    if (response.data.code !== 200) return

    const { dates, counts } = response.data.data

    // 转换日期格式为星期几
    const weekdays = dates.map(date => {
      const d = new Date(date)
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return weekdays[d.getDay()]
    })

    orderChart = echarts.init(orderChartRef.value)

    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: weekdays
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: counts,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#409eff'
          }
        }
      ]
    }

    orderChart.setOption(option)
  } catch (error) {
    console.error('获取订单趋势数据失败:', error)
  }
}

// 获取用户增长数据并初始化图表
const initUserChart = async () => {
  if (!userChartRef.value) return

  try {
    const response = await axios.get('http://localhost:8889/api/admin/dashboard/user-growth')
    if (response.data.code !== 200) return

    const { months, counts } = response.data.data

    userChart = echarts.init(userChartRef.value)

    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: counts,
          type: 'bar',
          itemStyle: {
            color: '#67c23a'
          }
        }
      ]
    }

    userChart.setOption(option)
  } catch (error) {
    console.error('获取用户增长数据失败:', error)
  }
}

// 窗口大小改变时重置图表大小
const handleResize = () => {
  if (orderChart) {
    orderChart.resize()
  }
  if (userChart) {
    userChart.resize()
  }
}

onMounted(() => {
  // 获取统计数据
  fetchDashboardStats()

  // 初始化图表
  initOrderChart()
  initUserChart()

  // 监听窗口大小改变
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 销毁图表实例
  if (orderChart) {
    orderChart.dispose()
  }
  if (userChart) {
    userChart.dispose()
  }

  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<script>
export default {
  name: 'HomeIndex'
}
</script>

<style scoped>
.home-container {
  min-height: calc(100vh - 80px);
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  border-radius: 8px;
}

.data-content {
  display: flex;
  align-items: center;
}

.data-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
}

.user-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.shop-icon {
  background-color: #fff7e6;
  color: #fa8c16;
}

.goods-icon {
  background-color: #f9f0ff;
  color: #722ed1;
}

.order-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.data-info .data-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.data-info .data-number {
  font-size: 24px;
  font-weight: bold;
}

.quick-actions {
  margin-bottom: 20px;
  border-radius: 8px;
}

.quick-item-col {
  display: flex;
}

.quick-item {
  flex: 1;
  text-align: center;
  padding: 20px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.quick-item:hover,
.quick-item:focus {
  background-color: #f0f9ff;
  transform: translateY(-3px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  outline: none;
}

.quick-item:active {
  transform: translateY(-1px);
}

.quick-item .el-icon {
  font-size: 24px;
  display: block;
  margin-bottom: 10px;
  transition: transform 0.2s;
}

.quick-item:hover .el-icon {
  transform: scale(1.1);
}

.quick-item span {
  font-size: 14px;
}

.chart-area .el-card {
  border-radius: 8px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>